<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="巡检单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="recordNumber">
              <a-input v-model="model.recordNumber" placeholder="保存自动生成" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="标准名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="standardCode">
              <j-search-select-tag
                @change="handleInspectionStandardChange"
                v-model="model.standardId"
                dict="qms_inspection_standard,standard_name,id" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="计划单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="planNumber">
              <j-search-select-tag v-model="model.planNumber" dict="tsl_pro_workshop_plan,code,code" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <j-vxe-table
              style="margin: 10px 0"
              keep-source
              :ref="refKeys[0]"
              :loading="inspectionRecordStandardItemTable.loading"
              :columns="inspectionRecordStandardItemTable.columns"
              :dataSource="inspectionRecordStandardItemTable.dataSource"
              :maxHeight="300"
              :disabled="formDisabled"
              :rowNumber="true"
              :rowSelection="!formDisabled"
              :toolbar="true"
              :toolbarConfig="{
                slots: ['prefix', 'suffix'],
                btn: ['remove', 'clearSelection'],
              }"
            />
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="巡检结果" :labelCol="labelCol2" :wrapperCol="wrapperCol" prop="result">
              <j-dict-select-tag type="radio" v-model="model.result" dictCode="qc_inspection_result" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if="!formDisabled">
            <a-form-model-item label="附件" :labelCol="labelCol2" :wrapperCol="wrapperCol" prop="file">
              <j-upload
                v-if="!formDisabled"
                :value="inspectionRecordFileTable.dataSource"
                :returnUrl="false"
                @change="handleFileChange" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="备注" :labelCol="labelCol2" :wrapperCol="wrapperCol" prop="remark">
              <a-textarea v-model="model.remark" rows="4" placeholder="请输入备注" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <div v-if="formDisabled">附件信息</div>
    <file-table-list
      style="margin-bottom: 10px"
      v-if="formDisabled"
      :loading="inspectionRecordFileTable.loading"
      :dataSource="inspectionRecordFileTable.dataSource"
      :disabled="formDisabled"
      :rowNumber="true"
      :toolbar="true" />
  </a-spin>
</template>

<script>

import { getAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import $file from '@/libs/globalFunction/file'
import FileTableList from '@comp/warehouse/FileTableList.vue'

export default {
  name: 'InspectionRecordForm',
  mixins: [JVxeTableModelMixin],
  components: {
    FileTableList,
    JFormContainer
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 2 }
      },
      model: {
        result: '1'
      },
      validatorRules: {
        result: [
          { required: true, message: '请选择巡检结果!' }
        ]
      },
      refKeys: ['inspectionRecordStandardItem'],
      tableKeys: ['inspectionRecordStandardItem'],
      // 巡检记录标准项表
      inspectionRecordStandardItemTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '检验项目',
            key: 'itemName',
            type: JVXETypes.normal,
            width: '200px'
          },
          {
            title: '巡检标准',
            key: 'qualityStandard',
            type: JVXETypes.normal,
            width: '200px'
          },
          {
            title: '巡检结果',
            key: 'result',
            type: JVXETypes.textarea,
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          }
        ]
      },
      // 巡检记录附件表
      inspectionRecordFileTable: {
        loading: false,
        dataSource: [],
      },
      url: {
        add: '/qms/inspection/inspection-record/add',
        edit: '/qms/inspection/inspection-record/edit',
        queryById: '/qms/inspection/inspection-record/queryById',
        inspectionRecordStandardItem: {
          list: '/qms/inspection/inspection-record/queryInspectionRecordStandardItemByMainId'
        },
        inspectionRecordFile: {
          list: '/qms/inspection/inspection-record/queryInspectionRecordFileByMainId'
        },
        inspectionStandardItem: {
          list: '/qms/inspection/inspection-standard/queryInspectionStandardItemByMainId'
        }
      },
      fileList: []
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    }
  },
  created() {
  },
  methods: {
    add() {
      this.addBefore()
      this.edit({})
    },
    addBefore() {
      this.inspectionRecordStandardItemTable.dataSource = []
      this.inspectionRecordFileTable.dataSource = []
    },
    getAllTable() {
      let values = this.tableKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {
      })
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.inspectionRecordStandardItem.list, params, this.inspectionRecordStandardItemTable)
        this.requestSubTableData(this.url.inspectionRecordFile.list, params, this.inspectionRecordFileTable, (res) => {
          if (this.inspectionRecordFileTable.dataSource && this.inspectionRecordFileTable.dataSource.length > 0) {
            this.inspectionRecordFileTable.dataSource.forEach(item => {
              this.$set(item, 'fileSizeFormat', $file.calculateFileSize(item.fileSize))
            })
          }
        })
      }
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([]).then(() => {
          resolve(allValues)
        }).catch(e => {
          console.error(e)
        })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        inspectionRecordStandardItemList: allValues.tablesValue[0].tableData.map(item => {
          return {
            ...item,
            id: null
          }
        }),
        inspectionRecordFileList: this.inspectionRecordFileTable.dataSource.map(item => {
          return {
            ...item,
            id: null
          }
        })
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    handleInspectionStandardChange(value) {
      const params = { id: value }
      getAction(this.url.inspectionStandardItem.list, params).then(res => {
        let { result } = res
        if (result) {
          this.inspectionRecordStandardItemTable.dataSource = result.map(item => {
            return {
              inspectionStandardId: item.inspectionStandardId,
              itemName: item.itemName,
              qualityStandard: item.qualityStandard,
              result: ''
            }
          })
        }
      })
    },
    handleFileChange(fileList) {
      if (!fileList || fileList.length <= 0) {
        return
      }
      this.inspectionRecordFileTable.dataSource = fileList
    },
    handleSubmit() {
      this.model.status = '1'
      this.handleOk()
    }
  }
}
</script>

<style scoped>
</style>